<template>
  <el-card
    shadow="never"
    style="margin-top: 10px"
    v-if="canHandle"
    v-loading="loading"
  >
    <div>
      <el-radio v-model="isForward" :label="false">处理</el-radio>
      <el-radio v-model="isForward" :label="true">转发</el-radio>
    </div>
    <br />
    <div v-if="!isForward">
      <el-form label-position="top">
        <el-form-item label="表单数据">
          <el-input
            type="textarea"
            :rows="2"
            placeholder="表单数据（与主流程不同，每一步都可能有当前的处理表单数据）"
            v-model="workStep.formData"
          ></el-input>
        </el-form-item>

        <el-form-item label="批语">
          <el-input
            type="textarea"
            :rows="1"
            placeholder="批语 "
            v-model="workStep.comment"
          ></el-input>
        </el-form-item>

        <el-form-item label="附件">
          <Uploader @file-uploaded="handleUploadSuccess"/>
        </el-form-item>

        <el-form-item>
          <div>
            <el-radio v-model="isPass" :label="true">通过</el-radio>
            <el-radio v-model="isPass" :label="false">驳回</el-radio>
          </div>
        </el-form-item>

        <el-form-item label="驳回节点" v-if="!isPass">
          <el-select
            placeholder="驳回节点"
            size="mini"
            v-model="workStep.rejectToNodeId"
          >
            <el-option
              v-for="item in rejectNodes"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            size="mini"
            @click="() => (isPass ? passApprove() : rejectApprove())"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </div>
    <div v-else>
      <SelectorUser
        :user-selector="userSelector"
        :users="users"
        :index="index"
        v-for="(userSelector, index) in userSelectors"
        :key="index"
        @change="onNodeUserChange"
      />
      <br />
      <el-button type="danger" size="mini" @click="forwardProve"
        >转发/代办</el-button
      >
    </div>
  </el-card>
  <div style="text-align: center; padding: 20px"  v-if="!canHandle">
    <el-text>没有可处理的步骤</el-text>
  </div>
    
</template>

<script setup>
import { ref, watch, computed, nextTick, onMounted } from "vue";
import SelectorUser from "./SelectorUser.vue";
import { useWorkTaskStore } from "@/stores/workTask";
import { useAppUserStore } from "@/stores/appUser";
import Uploader from "./Uploader.vue";
import usePostRefresh from "@/hooks/usePostRefresh";

const emit = defineEmits(["step-update"]);
const props = defineProps({
  taskId: {
    default: "",
  },
});

const { postRefresh } = usePostRefresh();

const isForward = ref(false);
const isPass = ref(true);
const workStep = ref({
  id: "",
  formData: "",
  comment: "",
  rejectToNodeId: "",
});


const loading = ref(false);
const userSelectors = ref([{}]);
const users = ref([]);

const rejectNodes = ref([]);

const canHandle = computed(() => {
  return workStep.value.id && workStep.value.id.length > 0;
});

watch(
  () => props.taskId,
  () => {
    reload();
  },
  { deep: true }
);
const appUserStore = useAppUserStore();
const currentUserId = computed(() => {
  return appUserStore.currentUser?.id;
});

watch(
  () => currentUserId,
  () => {
    reload();
  },
  { deep: true }
);

const workTaskStore = useWorkTaskStore();

const reload = async () => {
  const steps = await getPenddingTaskStepsOfWorkTask(props.taskId);
  if (steps && steps.length > 0) {
    workStep.value.id = steps[0].id;
    getRejectNodes(workStep.value.id);
  } else {
    workStep.value.id = "";
  }
  workStep.value.comment = "";
  workStep.value.formData = "";
  workStep.value.rejectToNodeId = "";
  workStep.value.resourceIds = "";

  isForward.value = false;
  isPass.value = true;
  emit("step-update", workStep.value);
};

const onNodeUserChange = (val) => {
  userSelectors.value[val.index] = val.selector;
  users.value = val.users;
};

const passApprove = async () => {
  loading.value = true;
  const data = {
    workTaskId: props.taskId,
    stepId: workStep.value.id,
    comment: workStep.value.comment,
    resourceIds: workStep.value.resourceIds,
    formData: workStep.value.formData,
  };

  await workTaskStore
    .passProve(data)
    .then((res) => {
      loading.value = false;
      postRefresh();
      reload();
    })
    .catch((e) => {
      loading.value = false;
    });
};

const rejectApprove = async () => {
  loading.value = true;
  const data = {
    workTaskId: props.taskId,
    stepId: workStep.value.id,
    comment: workStep.value.comment,
    resourceIds:workStep.value.resourceIds,
    rejectToNodeId: workStep.value.rejectToNodeId,
  };
  if (data.rejectToNodeId == "") {
    data.rejectToNodeId = null;
  }
  await workTaskStore
    .rejectProve(data)
    .then((res) => {
      loading.value = false;
      postRefresh();
      reload();
    })
    .catch((e) => {
      loading.value = false;
    });
};
const forwardProve = async () => {
  loading.value = true;
  const data = {
    workTaskId: props.taskId,
    stepId: workStep.value.id,
    comment: workStep.value.comment,
    resourceIds: workStep.value.resourceIds,
    userSelectors: userSelectors.value,
    users: users.value,
  };
  await workTaskStore
    .forwardProve(data)
    .then((res) => {
      loading.value = false;
      postRefresh();
      reload();
    })
    .catch((e) => {
      loading.value = false;
    });
};
const getRejectNodes = async (stepId) => {
  rejectNodes.value = [];
  await workTaskStore
    .GetRejectNodes({ workStepId: stepId })
    .then((res) => {
      rejectNodes.value = res;
    })
    .catch((e) => {
      loading.value = false;
    });
};
const getPenddingTaskStepsOfWorkTask = async (taskId) => {
  loading.value = true;
  const res = await workTaskStore.getPenddingTaskStepsOfWorkTask({
    worktaskId: taskId,
  });
  loading.value = false;
  return res;
};


const handleUploadSuccess = (fileIds, res) => {
  workStep.value.resourceIds = fileIds.join(',');
}

onMounted(() => {
  reload();
});

</script>

<style></style>
